<template>
    <div class="org-tree-container h-full">
        <a-card class="h-full">
            <header class="p-2.5">
                <a-row :gutter="[0, 16]">
                    <a-col :span="24" v-if="!props.tenantId">
                        <a-select
                            v-if="userInfoStore.state.userInfos.accountType == 999" 
                            v-model:value="state.formState.tenantId"
                            placeholder="请选择租户"
                            class="w-full"
                            @change="initDataTree"
                            allowClear
                        >
                            <a-select-option
                                v-for="item in state.tenantList"
                                :key="item.value"
                                :value="item.value"
                            >
                                {{ item.label }}
                            </a-select-option>
                        </a-select>
                    </a-col>
                    <a-col :span="24">
                        <a-input-search 
                            v-model:value="state.formState.filterText" 
                            placeholder="机构名称"
                            allowClear
                        />
                    </a-col>
                </a-row>
            </header>
            
            <a-tree
                ref="treeRef"
                v-if="!state.loading"
                v-model:expanded-keys="state.expandedKeys"
                v-model:checked-keys="state.checkedKeys"
                v-model:selected-keys="state.selectedKeys"
                :auto-expand-parent="state.autoExpandParent"
                :tree-data="state.orgData"
                :fieldNames="{key:'id'}"
                :checkable="props.checkable"
                @expand="onExpand"
                @select="(selectedKeys: string[], info: any) => nodeClick(info.node.dataRef)"
                @check="onCheck"
            >
                <template #title="{ name }">
                    <span v-if="name.indexOf(state.formState.filterText) > -1">
                    {{ name.substring(0, name.indexOf(state.formState.filterText)) }}
                    <span style="color: #f50">{{ state.formState.filterText }}</span>
                    {{ name.substring(name.indexOf(state.formState.filterText) + state.formState.filterText.length) }}
                    </span>
                    <span v-else>{{ name }}</span>
                </template>
            </a-tree>
        </a-card>
    </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, watch,ref, nextTick, onBeforeMount } from 'vue';
import { useUserInfo } from '@/stores/userInfo';
import { apiSysTenantListGet } from '@/api/sys/sysTenant';
import type { ResType } from '@/api/types';
import type { TenantListType } from '../../onlineUser/type';
import type { OrgTreeState, OrgDataType } from '../type';
import { apiSysOrgListGet } from '@/api/sys/sysOrg';


const props = withDefaults(defineProps<{
    tenantId?: number | undefined,
    checkable?: boolean,
}>(),{
    checkable:false
})

const emits =defineEmits<{
    (e:"node-click",node:any):void
}>();

const treeRef = ref()

const userInfoStore = useUserInfo()
const dataList: OrgDataType[] = [];

const state = reactive<OrgTreeState>({
    formState: {
        filterText:"",
        tenantId:props.tenantId
    },
    tenantList:[],
    orgData:[],
    loading:false,
    expandedKeys:[], //展开值
    autoExpandParent:false,
    checkedKeys:[], //多选框选中值
    selectedKeys:[] // 选中值
});

const onFinish = (values: any) => {
    console.log('Success:', values);
};

const generateList = (data: OrgDataType[]) => {
    for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const id = node.id;
        dataList.push({ ...node });
        if (node.children) {
            generateList(node.children);
        }
    }
};

const getParentKey = (key: number, tree: OrgDataType[]): number | undefined => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some(item => item.id === key)) {
                parentKey = node.id;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey;
};
const initDataTree = async () => {
    state.loading = true;
    const res = await apiSysOrgListGet(0, undefined, undefined, undefined, state.formState.tenantId) as ResType<OrgDataType[]>;
    state.orgData = res.data.result;
    generateList(state.orgData);
    state.loading = false;
}
const onExpand = (keys: string[]) => {
    state.expandedKeys = keys;
    state.autoExpandParent = false
};
onBeforeMount(async () => {
    if (userInfoStore.state.userInfos.accountType === 999) {
        const res = await apiSysTenantListGet() as ResType<TenantListType>;
        state.tenantList = res.data.result;
    }
    initDataTree();
});

watch(() => state.formState.filterText, value => {
    const expanded = dataList
        .map(item => {
            if (item.name.indexOf(value) > -1) {
                return getParentKey(item.id, state.orgData);
            }
            return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
    state.expandedKeys = expanded as number[];
    state.autoExpandParent = true;
});

const nodeClick=(node:any)=>{
    emits('node-click',node)
}

const onCheck = (checkedKeys: any[]) => {
    console.log(checkedKeys);
    
};
const setCheckedKeys = (keys: number[]) => {
    const isArray = Array.isArray(keys); // 判断是否是数组
    state.checkedKeys = keys
    state.selectedKeys = keys
    state.expandedKeys = keys
    state.autoExpandParent = true;
}

const getCheckedKeys = ()=>{
    return state.checkedKeys
}

defineExpose({
    setCheckedKeys,
    getCheckedKeys
})
</script>

<style lang="scss" scoped>
.org-tree-container{
    :deep(.ant-card-body){
        padding: 0;
    }
}
</style>